/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.icanci.loopstack.damc.admin.biz.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

import cn.icanci.loopstack.damc.admin.biz.service.AppService;
import cn.icanci.loopstack.damc.admin.biz.service.ClassScriptService;
import cn.icanci.loopstack.damc.admin.biz.service.PubSubService;
import cn.icanci.loopstack.damc.admin.biz.service.RegisterTableService;
import cn.icanci.loopstack.damc.admin.biz.thread.RegisterTableRefreshCache;
import cn.icanci.loopstack.damc.admin.biz.thread.TriggerThread;
import cn.icanci.loopstack.damc.admin.common.model.base.AppVO;
import cn.icanci.loopstack.damc.admin.common.model.base.ClassScriptVO;
import cn.icanci.loopstack.damc.admin.common.model.base.RegisterTableVO;
import cn.icanci.loopstack.damc.spi.model.pubsub.DisposableRunnerDTO;
import cn.icanci.loopstack.damc.spi.model.pubsub.DisposableRunnerTypeEnum;
import cn.icanci.loopstack.damc.spi.model.pubsub.PublishDTO;
import cn.icanci.loopstack.damc.spi.model.pubsub.PublishTypeEnum;
import cn.icanci.loopstack.damc.spi.model.refresh.RefreshCell;

/**
 * @author icanci
 * @since 1.0 Created in 2025/05/17 07:34
 */
@Service("pubSubService")
public class PubSubServiceImpl implements PubSubService {
    @Resource
    private RegisterTableService registerTableService;
    @Resource
    private ClassScriptService   classScriptService;
    @Resource
    private AppService           appService;

    /**
     * 发布
     *
     * @param appCode   appCode
     * @param clazzName 需要被发布的类全限定类名
     */
    @Override
    public void publish(String appCode, String clazzName) {
        AppVO appVO = appService.queryByCode(appCode);
        if (appVO == null || appVO.isDeleted()) {
            return;
        }
        List<RegisterTableVO> registerTables = registerTableService.queryEnableByAppCode(appCode);
        if (CollectionUtils.isEmpty(registerTables)) {
            return;
        }
        // 如果 classScripts 为空，则说明是清除所有的配置项
        List<ClassScriptVO> classScripts = classScriptService.queryEnableByAppCodeAndClazzName(appCode, clazzName);
        List<RegisterTableRefreshCache> caches = Lists.newArrayList();

        PublishDTO publishDTO = new PublishDTO();
        publishDTO.setClasses(buildClasses(clazzName, classScripts));

        for (RegisterTableVO registerTable : registerTables) {
            RegisterTableRefreshCache cache = new RegisterTableRefreshCache();
            cache.setRegisterTable(registerTable);
            cache.setPublishDTO(publishDTO);
            cache.setPublishType(PublishTypeEnum.CLASS_SCRIPT);
            caches.add(cache);
        }

        TriggerThread.trigger(caches);
    }

    /**
     * disposable
     *
     * @param appCode    appCode
     * @param script     script
     * @param runnerType runnerType
     */
    @Override
    public void disposable(String appCode, String script, String runnerType) {
        DisposableRunnerTypeEnum type = DisposableRunnerTypeEnum.getByCode(runnerType);
        if (type == null) {
            throw new IllegalArgumentException("un support runnerType:" + runnerType);
        }
        AppVO appVO = appService.queryByCode(appCode);
        if (appVO == null || appVO.isDeleted()) {
            return;
        }
        List<RegisterTableVO> registerTables = registerTableService.queryEnableByAppCode(appCode);
        if (CollectionUtils.isEmpty(registerTables)) {
            return;
        }

        if (type == DisposableRunnerTypeEnum.COLONY) {
            for (RegisterTableVO registerTable : registerTables) {
                doDisposableRunner(registerTable, script);
            }
        } else {
            RegisterTableVO registerTableVO = registerTables.iterator().next();
            doDisposableRunner(registerTableVO, script);
        }
    }

    private List<RefreshCell> buildClasses(String clazzName, List<ClassScriptVO> classScripts) {
        if (CollectionUtils.isEmpty(classScripts)) {
            return defaultClearCells(clazzName);
        }
        Map<String, List<ClassScriptVO>> group = classScripts.stream().collect(Collectors.groupingBy(ClassScriptVO::getClazzName));
        List<RefreshCell> refreshCells = Lists.newArrayList();
        for (Map.Entry<String, List<ClassScriptVO>> entry : group.entrySet()) {
            String key = entry.getKey();

            RefreshCell cell = getRefreshCell(entry, key);

            refreshCells.add(cell);
        }
        return refreshCells;
    }

    private List<RefreshCell> defaultClearCells(String clazzName) {
        RefreshCell cell = new RefreshCell();
        cell.setClazz(clazzName);
        return Lists.newArrayList(cell);
    }

    /**
     * getRefreshCell
     * 
     * @param entry entry
     * @param key key
     * @return RefreshCell
     */
    private static RefreshCell getRefreshCell(Map.Entry<String, List<ClassScriptVO>> entry, String key) {
        List<ClassScriptVO> value = entry.getValue();
        List<RefreshCell.Cell> cells = Lists.newArrayList();
        for (ClassScriptVO classScriptVO : value) {
            RefreshCell.Cell cell = new RefreshCell.Cell();
            cell.setMethodName(classScriptVO.getMethodName());
            cell.setDescriptor(classScriptVO.getDescriptor());
            cell.setScript(classScriptVO.getScript());
            cells.add(cell);
        }

        RefreshCell cell = new RefreshCell();
        cell.setClazz(key);
        cell.setCells(cells);
        return cell;
    }

    /**
     * 执行任务
     *
     * @param registerTable registerTable
     * @param script script
     */
    private void doDisposableRunner(RegisterTableVO registerTable, String script) {
        RegisterTableRefreshCache cache = new RegisterTableRefreshCache();
        cache.setRegisterTable(registerTable);
        cache.setPublishType(PublishTypeEnum.DISPOSABLE_SCRIPT_RUNNER);
        cache.setDisposableRunnerDTO(new DisposableRunnerDTO(registerTable.getAppCode(), script));
        TriggerThread.trigger(cache);
    }
}
